/**  
 * All rights Reserved, Designed By daiw
 * @Title:  SysUserServiceImpl.java   
 * @Package org.easy.system.manage.service.impl   
 * @Description:    TODO (用一句话描述该文件做什么)   
 * @author: daiw     
 * @date:   2019年10月17日 下午3:44:17   
 * @Copyright: 2019 daiw Inc. All rights reserved. 
 */
package org.easy.system.manage.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.easy.system.manage.config.PropertieConfig;
import org.easy.system.manage.config.RedisKey;
import org.easy.system.manage.dao.SysUserMapper;
import org.easy.system.manage.dto.SaveUserParam;
import org.easy.system.manage.dto.UserQueryParam;
import org.easy.system.manage.entity.SysMenu;
import org.easy.system.manage.entity.SysRole;
import org.easy.system.manage.entity.SysUser;
import org.easy.system.manage.service.SysMenuService;
import org.easy.system.manage.service.SysRoleService;
import org.easy.system.manage.service.SysUserService;
import org.easyframework.core.entity.ProcessResult;
import org.easyframework.core.utils.AESUtil;
import org.easyframework.core.utils.BeanUtil;
import org.easyframework.core.utils.MD5Util;
import org.easyframework.core.utils.ValidationUtils;
import org.easyframework.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.system.manage.facade.entity.UserInfoDto;
import org.system.manage.facade.entity.UserInfoSession;
import org.system.manage.facade.entity.UserPrivilageDto;
import org.system.manage.facade.entity.UserRoleDto;
import org.system.manage.facade.entity.ValidLoginResult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

/**
 * @ClassName: SysUserServiceImpl
 * @Description:
 * @author: daiw
 * @date: 2019年10月17日 下午3:44:17
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private PropertieConfig propertieConfig;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private RedisUtil redisUtil;

	@Override
	public ProcessResult<?> insert(SaveUserParam param, UserInfoDto userInfoDto) {
		ProcessResult<String> validateResult = ValidationUtils.validate(param);
		if (validateResult.isFailed()) {
			return validateResult;
		}
		SysUser entity = BeanUtil.convert(param, SysUser.class);
		if (entity == null) {
			return ProcessResult.getInstFailed("用户信息有误！");
		}
		try {
			entity.setSalt(UUID.randomUUID().toString().substring(0, 16));
			String decryptPwd = AESUtil.Decrypt(propertieConfig.getDefaultPassword(), propertieConfig.getDefaultKey());
			entity.setPassword(MD5Util.getMD5(decryptPwd + entity.getSalt()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		entity.setUserName(entity.getLoginName());
		entity.setCreateBy(userInfoDto.getLoginName());
		entity.setCreateTime(new Date());
		int count = sysUserMapper.insertSelective(entity);
		return ProcessResult.getInst(count > 0);
	}

	@Override
	public ProcessResult<?> update(SaveUserParam param) {
		SysUser entity = BeanUtil.convert(param, SysUser.class);
		if (entity == null) {
			return ProcessResult.getInstFailed("用户信息有误！");
		}
		int count = sysUserMapper.updateByPrimaryKeySelective(entity);
		return ProcessResult.getInst(count > 0);
	}

	@Override
	public ValidLoginResult validLogin(String loginInfo) throws Exception {
		JSONObject loginInfoJson = JSON.parseObject(AESUtil.Decrypt(loginInfo, propertieConfig.getDefaultKey()));
		SysUser user = sysUserMapper.selectByLoginName(loginInfoJson.getString("loginName"));
		if (MD5Util.getMD5(loginInfoJson.getString("password") + user.getSalt()).equals(user.getPassword())) {
			UserInfoSession userInfoSession = new UserInfoSession();
			// 验证通过，获取角色信息
			List<SysRole> roles = sysRoleService.selectRolesByUserId(user.getUserId());
			List<UserRoleDto> userRoles = BeanUtil.convertList(roles, UserRoleDto.class);
			userInfoSession.setUserRoleDto(userRoles);
			// 获取权限信息
			List<Long> roleIds = userRoles.stream().map(role -> role.getRoleId()).collect(Collectors.toList());
			if (!CollectionUtils.isEmpty(roleIds)) {
				List<SysMenu> userPrivilages = sysMenuService.selectPrivilagesByRoleIds(roleIds);
				List<UserPrivilageDto> privilages = BeanUtil.convertList(userPrivilages, UserPrivilageDto.class);
				userInfoSession.setUserPrivilageDto(privilages);
			}
			// 获取用户信息
			userInfoSession.setUserInfoDto(BeanUtil.convert(user, UserInfoDto.class));
			redisUtil.setObj(RedisKey.USER_SESSION_KEY + user.getUserId(), userInfoSession, 604800L);
			return new ValidLoginResult(user.getUserId(), user.getUserName());
		}
		return null;
	}

	@Override
	public ProcessResult<List<SysUser>> queryByPage(UserQueryParam queryParam) {
		PageHelper.offsetPage(queryParam.getPageIndex(), queryParam.getPageSize(), true);
		List<SysUser> users = sysUserMapper.queryByPage(queryParam);
		return ProcessResult.getInstSuccess(users);
	}

	@Override
	public ProcessResult<SysUser> queryDetail(Long userId) {
		SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
		return ProcessResult.getInstSuccess(sysUser);
	}

	@Override
	public ProcessResult<?> updateStatus(Long userId, Integer status) {
		SysUser updateCondition = new SysUser();
		updateCondition.setUserId(userId);
		updateCondition.setStatus(status);
		int count = sysUserMapper.updateByPrimaryKeySelective(updateCondition);
		return ProcessResult.getInst(count > 0);
	}

}
